package com.fuqi.android.zhongcai.utils;


/**
 * Created by juner on 2014/8/29.
 */

import android.app.Activity;

import com.fuqi.android.zhongcai.application.UniApplication;
import com.fuqi.android.zhongcai.base.ApiUrl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class FormImgsUtils {


    private static FormImgsUtils fileUpload;
    private static UploadCallback uploadCallback;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    private String upLoadServerUri = ApiUrl.getOrderHandleUrl();
    private HashMap<String, String> params;
    private int serverResponseCode = 500;
    private List<String> localFilePath;
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            uploadFile(localFilePath);
        }
    };
    private FormImgsUtils(Activity activity) {
        uploadCallback = (UploadCallback) activity;
    }

    public static FormImgsUtils getInstance(Activity activity) {

        if (fileUpload == null) {

            fileUpload = new FormImgsUtils(activity);
        }

        return fileUpload;

    }

    public void request(final List<String> localFilePath, HashMap<String, String> params) {
        this.localFilePath = localFilePath;
        this.params = params;
        new Thread(networkTask).start();

    }

    public int uploadFile(final List<String> localFilePath) {

        sendStartMsg();
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        FileInputStream fileInputStream = null;
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 2 * 1024 * 1024;
        try {

            for (int i = 0; i < localFilePath.size();i ++){
            String fileName = localFilePath.get(i).substring(localFilePath.lastIndexOf("/") + 1);
        File sourceFile = new File(localFilePath.get(i));
        if (!sourceFile.isFile()) {
            LogUtils.d("Source File not exist :" + localFilePath);
            return 0;
        } else {


            // open a URL connection to the Servlet
            fileInputStream  = new FileInputStream(sourceFile);
            LogUtils.d("fileInputStream");
            URL url = new URL(upLoadServerUri);
            LogUtils.d("upLoadServerUri: " + upLoadServerUri + " sourceFileUri: " + localFilePath);
            LogUtils.d("url");
            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            String time = String.valueOf(System.currentTimeMillis() / 1000);
            conn.setRequestProperty("TOKEN", UniApplication.getInstance().getUserInfo().getToken());
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"PICS\";" +
                    "filename= \"" + fileName + "\""
                    + lineEnd);
            dos.writeBytes(lineEnd);
            LogUtils.d("writeBytes");
            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            LogUtils.i("juner bytesRead: " + bytesRead);
            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                LogUtils.d("bytesRead");
            }
            LogUtils.d("while");
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            //dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        }

            }
                StringBuilder sb = new StringBuilder();
                sb.append(twoHyphens + boundary + lineEnd);

            Iterator iter = params.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    sb.append("Content-Disposition: form-data; name=\""+ key + "\"" + lineEnd);
                    sb.append(lineEnd);
                    sb.append(val + lineEnd);

                    }


                dos.writeBytes(sb.toString());
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                LogUtils.d("serverResponseMessage: " + serverResponseCode);
                LogUtils.i("HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseMessage);
                if (serverResponseCode != 200) {
                    LogUtils.d("upload error");
                    sendErrorMsg();
                }else if(serverResponseCode == 500){

                    ActivityUtils.toast("上传图片失败");

                }

                InputStream is = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                final String result = br.readLine();
                LogUtils.i(" data-form result:" + result);

//                final AvatarData avatarData = GsonHelper.parseJsonObject(result, AvatarData.class);

                if (serverResponseCode == 200) {
//                    LogUtils.i("upload success " + avatarData.getData());
//                    sendSuccessMsg(avatarData.getData());
                }

                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();



            sendFinishMsg();
            return serverResponseCode;
        } catch (MalformedURLException ex) {
            LogUtils.d("MalformedURLException");
            sendErrorMsg();
            ex.printStackTrace();
            LogUtils.i("error: " + ex.getMessage());
        } catch (Exception e) {
            LogUtils.d("Exception: " + e.toString());
            sendErrorMsg();
            e.printStackTrace();
        }

        return serverResponseCode;

    }

    private void sendStartMsg() {

        uploadCallback.onUploadStart();

    }


    private void sendFinishMsg() {

        uploadCallback.onUploadFinish();

    }

    private void sendSuccessMsg(String backUri) {

        uploadCallback.onUploadSuccess(backUri);

    }


    private void sendErrorMsg() {

        uploadCallback.onUploadError();

    }

    public interface UploadCallback {

        public void onUploadStart();

        public void onUploadFinish();

        public void onUploadSuccess(String avatarUrl);

        public void onUploadError();

    }

}
